| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { UserService } from '@/server/modules/users/user.service';
- import { z } from 'zod';
- import { authMiddleware } from '@/server/middleware/auth.middleware';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { AppDataSource } from '@/server/data-source';
- import { AuthContext } from '@/server/types/context';
- import { UserSchema } from '@/server/modules/users/user.entity';
- const userService = new UserService(AppDataSource);
- const GetParams = z.object({
- id: z.string().openapi({
- param: { name: 'id', in: 'path' },
- example: '1',
- description: '用户ID'
- })
- });
- const routeDef = createRoute({
- method: 'get',
- path: '/{id}',
- middleware: [authMiddleware],
- request: {
- params: GetParams
- },
- responses: {
- 200: {
- description: '成功获取用户详情',
- content: { 'application/json': { schema: UserSchema } }
- },
- 404: {
- description: '用户不存在',
- content: { 'application/json': { schema: ErrorSchema } }
- },
- 500: {
- description: '服务器错误',
- content: { 'application/json': { schema: ErrorSchema } }
- }
- }
- });
- const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- const { id } = c.req.valid('param');
- const user = await userService.getUserById(parseInt(id));
- if (!user) {
- return c.json({ code: 404, message: '用户不存在' }, 404);
- }
- return c.json(user, 200);
- } catch (error) {
- return c.json({
- code: 500,
- message: error instanceof Error ? error.message : '获取用户详情失败'
- }, 500);
- }
- });
- export default app;
|